import {getStorage, setStorage} from 'hcg-storage';

let shopCart = getStorage('shopCart') || {
	shopCart: [],
	checkAll: true
};
export default {
	state: shopCart,
	mutations: {
		addShopCart(state, goods) {
			state.shopCart.push(goods);
			setStorage('shopCart', state)
		},
		addCount(state, goods) {
			let myGoods = state.shopCart.find(item => item.propertyChildIdsStr === goods.propertyChildIdsStr);
			if (myGoods.count + goods.count > myGoods.stores) {
				return;
			}
			myGoods.count += goods.count;
			setStorage('shopCart', state)
		},
		removeItem(state, id) {
			let index = state.shopCart.findIndex(item => item.propertyChildIdsStr === id);
			state.shopCart.splice(index, 1);
			setStorage('shopCart', state)
		},
		removeCheck(state) {
			for (let index = 0; index < state.shopCart.length; index++) {
				if (state.shopCart[index].checked) {
					state.shopCart.splice(index, 1);
					index--;
				}
			}
			setStorage('shopCart', state)
		},
		changeCheckAll(state, check) {
			state.checkAll = check;
			state.shopCart.forEach(item => {
				item.checked = check;
			});
			setStorage('shopCart', state)
		},
		updateCheckAll(state, check) {
			state.checkAll = check;
			setStorage('shopCart', state)
		},
		clearShopCart(state) {
			state.shopCart = state.shopCart.filter(item => !item.checked);
			setStorage('shopCart', state)
		}
	},
	actions: {
		addShopCart({commit, state}, goods) {
			let flag = state.shopCart.some(item => item.propertyChildIdsStr === goods.propertyChildIdsStr);
			if (flag) {
				commit('addCount', goods);
			} else {
				commit('addShopCart', goods);
			}
		},
		removeItem({commit}, item) {
			commit('removeItem', item.propertyChildIdsStr);
		},
		changeCheckAll({commit}, check) {
			commit('changeCheckAll', check)
		},
		changeItemCheck({commit, state}) {
			let count = 0;
			state.shopCart.forEach(item => {
				if (item.checked) {
					count++;
				}
			});
			if (count === state.shopCart.length) {
				commit('updateCheckAll', true)
			} else {
				commit('updateCheckAll', false)
			}
		},
		clearShopCart({commit}) {
			commit('clearShopCart');
		}
	},
	getters: {
		allCount(state) {
			let count = 0;
			for (let item of state.shopCart) {
				count += item.count;
			}
			return count;
		},
		allTotal(state) {
			let total = 0;
			for (let item of state.shopCart) {
				if (item.checked) {
					total += item.count * item.price;
				}
			}
			return parseFloat(total.toFixed(2));
		}
	}
}
